const path = require("path");
const fs = require("fs");
const { copyDir, delDir } = require("./utils");
/**
 * 读取文件夹
 * @param {*} dirPath
 * @param {*} options
 * @returns
 */
function traverseDir(dirPath, options) {
  let fileList = [];
  const dirs = fs.readdirSync(dirPath) || [];

  for (let dir of dirs) {
    const fullPath = path.join(dirPath, dir);
    if (
      options.includeDir &&
      !options.includeDir.some((item) => {
        const includePath = path.join(options.globalPath, item);
        return (
          fullPath.startsWith(includePath) || includePath.startsWith(fullPath)
        );
      })
    ) {
      console.log("跳出");
      continue;
    }
    const stats = fs.statSync(fullPath);
    if (stats.isDirectory()) {
      fileList = fileList.concat(traverseDir(fullPath, options));
    } else if (options.exts.includes(path.extname(fullPath))) {
      if (options.includeFile === undefined) {
        // 
        ;
      } else {
        if (
          !options.includeFile ||
          (options.includeFile &&
            !options.includeFile.some((item) => fullPath.includes(item)))
        ) {
          continue;
        }
      }

      fileList.push(fullPath.replace(options.globalPath, ""));
    }
  }
  return fileList;
}

/**
 * 创建上下文
 * @param {*} context
 * @returns
 */
const createContext = async (config) => {
  config.distDir = path.join(config.output, config.distDir);
  config.translateDir = path.join(config.output, config.translateDir);
  config.translateEnDir = path.join(config.output, config.translateEnDir);
  config.pageDir = path.join(config.output, config.pageDir);
  // config
  const context = JSON.parse(JSON.stringify(config));

  delDir(path.join(config.output, "tempPage"));
  await Promise.all(
    context.includeDir.map((dir) =>
      copyDir(
        path.join(context.projectPath, dir),
        path.join(config.output, "tempPage", dir),
        async (destPath) => {
          const prettier = require("prettier");
          const fileContent = fs.readFileSync(destPath, "utf-8");
          const formattedCode = await prettier.format(fileContent, {
            parser: "vue",
            ...(config.prettier || {}),
            // 减少因自动缩进带来的文本分割
            printWidth: 9999,
          });
          fs.writeFileSync(destPath, formattedCode, "utf-8");
        }
      )
    )
  );
  context.projectPath = path.join(config.output, "tempPage");
  const files = traverseDir(context.projectPath, {
    globalPath: context.globalPath || context.projectPath,
    includeDir: context.includeDir,
    includeFile: context.includeFile,
    exts: context.exts,
  });
  console.log(`files total: ${files.length}`);
  const cwd = context.cwd || process.cwd();
  const dist = path.join(cwd, context.distDir);
  const translate = path.join(cwd, context.translateDir);
  const translateEn = path.join(cwd, context.translateEnDir);
  const pageDir = path.join(cwd, context.pageDir);
  // config
  return {
    ...context,
    cwd,
    files,
    catchTmp: {
      dist,
      translate,
      translateEn,
    },
    contextFiles: files.map((file) => {
      const pathParse = path.parse(file);
      let dir = pathParse.dir;
      dir = dir.replace(path.normalize(config.projectPath), "");
      let file2 = file.replace(path.normalize(config.projectPath), "");
      return {
        path: file,
        fullPath: path.join(context.projectPath, file2),
        // 抽离文件夹
        distDir: path.join(dist, dir),
        i18nFilePath: path.join(dist, dir, `${pathParse.name}.ts`),
        // 大模型转义中文
        translateDir: path.join(translate, dir),
        translatePath: path.join(translate, dir, `${pathParse.name}.ts`),
        // 大模型转义英文
        translateEnDir: path.join(translateEn, dir),
        translateEnPath: path.join(translateEn, dir, `${pathParse.name}.ts`),
        // 文件替换
        pageDir: path.join(pageDir, dir),
        pagePath: path.join(pageDir, dir, `${pathParse.name}${pathParse.ext}`),
      };
    }),
  };
};

module.exports = createContext;
